package com.example.modulejsonui.util.thread;

import com.example.modulejsonui.net.JsonNet;
import com.lamfire.json.JSONObject;
import com.maoti.lib.net.ResponseResult;
import com.maoti.lib.net.interceptor.DefaultObserver;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Android Studio.
 * User: wsl
 * Date: 2020/12/15
 * Time: 3:41 PM
 * Description:
 */
public class UploadFile implements Runnable {
    private CountDownLatch downLatch;//计数器
    private String fileName;//文件名
    private OnThreadResultListener listener;//任务线程回调接口
    private int percent=0;//进度
    private Random mRandom;//随机数 模拟上传

    public UploadFile(CountDownLatch downLatch,String fileName,OnThreadResultListener listener){
        this.downLatch=downLatch;
        this.fileName=fileName;
        this.listener=listener;

        mRandom=new Random();
    }

    @Override
    public void run() {
        try {
            getNetJson(fileName);
        } catch (Exception e) {
            listener.onInterrupted();//被中断
        }
    }

    private void getNetJson(String url){
        JsonNet.getObjectJson(url, new DefaultObserver<JSONObject>() {
            @Override
            public void onSuccess(ResponseResult<JSONObject> result) {
                downLatch.countDown();
                listener.onFinish(result.getData());//顺利完成
            }

            @Override
            public void onException(int code, String eMsg) {
                listener.onInterrupted();//解析错误，被中断
//                listener.onProgressChange(percent);
            }
        });

    }
}